﻿"use strict";

Function.prototype.getName = function () {
    return this.name || this.toString().match(/function\s*([^(]*)\(/)[1];
};

String.prototype.trim = function () {
    return this.replace(/(^\s+)|(\s+$)/g, "");
};
/**
 * 命名空间定义
 *
 * @access public
 * @return void
 */
var PAGE = PAGE || {};

PAGE.namespace = function (ns_string) {
    var parts = ns_string.split('.'),
        parent = PAGE,
        i;
    if (parts[0] === 'PAGE') {
        parts = parts.slice(1);
    }
    for (i = 0; i < parts.length; i++) {
        if (typeof parent[parts[i]] === 'undefined') {
            parent[parts[i]] = {};
        }
        parent = parent[parts[i]];
    }
    return parent;
};

/**
 * 按钮工厂类 支持创建新对象和新类
 *
 * @access public
 * @return void
 */
function BtnMaker(options) {
    this.button = options.button || '';
    this.href = options.href || '';
    this.table = options.table || '#models-data';
    this.keyId = '';
    this.before = options.before || '';
    var that = this;
    $(this.button).bind('click', function () {
        var msg = $(this).attr('msg') ? $(this).attr('msg') : '确认删除此条数据？';
        that.skip(msg);
    });
};
// 按钮事件方法
BtnMaker.prototype.skip = function (msg) {
    this.setKeyId();
    var keyId = this.getKeyId(),
        url = this.href + (keyId ? '/' + keyId : '');
    if (this.before) {
        this.beforeAct(url, msg);
    } else {
        window.location.href = url;
    }
};

BtnMaker.prototype.setKeyId = function () {
    var check = $(this.table + ' >tbody tr').find('td:first span.checked input');
    var obj = this;
    this.keyId="";
    if (check.size() > 1) {
        check.each(function () {
            obj.keyId += '~' + $(this).val();
        });
        this.keyId = this.keyId.substr(1);
    } else if (check.size() === 1) {
        this.keyId = check.val();
    } else {
        this.keyId = null;
    }
    if (this.keyId === '') {
        this.keyId = check.val();
    }
};

BtnMaker.prototype.getKeyId = function () {
    return this.keyId;
};

BtnMaker.prototype.beforeAct = function (url, msg) {
    var content = "<form action='" + url + "' id='formdelete'></form>";
    var jump = $('[data-method-url]').attr('data-method-url');
    var divId = BtnMaker.view('', msg, content);
    $(this.button).attr('data-toggle', 'modal').attr('href', '#' + divId);
    $('#dialogSubmit').bind('click', function () {
        ajaxSubmitAndMsg.init('#formdelete', true, jump);
    });
};

// 存放按钮的实例
BtnMaker.instance = (function ($) {
    var btns = {};
    return {
        get: function (key) {
            //解决按钮不存在时获取实例对方法进行重写报错
            if ($('#' + key).length <= 0) {
                return {};
            }
            return btns[key];
        }
        , set: function (key, obj) {
            btns[key] = obj;
            return btns[key];
        }
    };
})(window.jQuery);

BtnMaker.view = function (divId, title, content) {
    var divId = divId || 'portlet-config',
        title = title || '',
        content = content || '',
        dialogObj = $('#' + divId),
        viewHtml = '<!-- BEGIN SAMPLE PORTLET CONFIGURATION MODAL FORM-->'
            + '<div class="modal fade" id="'
            + divId
            + '" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">'
            + '<div class="modal-dialog--">'
            + '<div class="modal-content">'
            + '<div class="modal-header">'
            + '<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>'
            + '<h4 class="modal-title">'
            + title
            + '</h4>'
            + '</div>'
            + '<div class="modal-body">'
            + content
            + '</div>'
            + '<div class="modal-footer">'
            + '<button type="button" class="btn blue" id="dialogSubmit">确认</button>'
            + '<button type="button" class="btn default" id="dialogCancel" data-dismiss="modal">关闭</button>'
            + '</div>'
            + '</div>'
            + '<!-- /.modal-content -->'
            + '</div>'
            + '<!-- /.modal-dialog -->'
            + '</div>'
            + '<!-- /.modal -->'
            + '<!-- END SAMPLE PORTLET CONFIGURATION MODAL FORM-->';
    if (dialogObj.length <= 0) {
        $('body').append(viewHtml);
    } else {
        dialogObj.find('.modal-title').html(title);
        dialogObj.find('.modal-body').html(content);
    }
    return divId;
}

// 静态工厂方法
BtnMaker.factory = function (type) {
    if (typeof type === "object" && type.button !== undefined) {
        var instance = BtnMaker.instance.get(type.button.substr(1));
        return instance ? instance : BtnMaker.instance.set(type.button.substr(1), new BtnMaker(type));
    }
    if (typeof type !== "function") {
        throw {
            name: "Error",
            message: type + " doesn't exist"
        };
    }
    var inst = BtnMaker.instance.get('C_' + type.getName());
    if (!inst) {
        inst = type;
        inst.prototype = BtnMaker.prototype;
        inst = new inst();
        BtnMaker.instance.set('C_' + type.getName(), inst);
    }
    return inst;
};

/**
 * 工具条亮暗控制
 */
var BtnToggleEffect = (function ($) {
    var initConf = $("[data-btnstatus]").attr('data-btnstatus');
    if (initConf === undefined || initConf === "") {
        pagelog("按钮相互影响参数未获取！");
        return false;
    }
    var Tools = function () {
        this.objTools = $('.actions');
        this.objBtns = this.objTools.find('.btn[id]');
        this.jsonInitConf = $.parseJSON(initConf);
        this.btnInit.apply(this);
    };
    Tools.prototype = {
        constructor: Tools,
        btnInit: function () {
            this.btnAssignEnable('init');
        },
        btnAllDisable: function () {
            this.objBtns.attr('disabled', 'disabled');
        },
        btnAllEnable: function () {
            this.objBtns.removeAttr('disabled');
        },
        btnEnable: function (btnStr) {
            $('#' + btnStr).removeAttr('disabled');
        },
        btnDisable: function (btnStr) {
            $('#' + btnStr).attr('disabled', 'disabled');
        },
        btnAssignEnable: function (btnKey) {
            var that = this;
            $.each(that.jsonInitConf[btnKey], function (k, v) {
                that.btnEnable(v);
            });
        },
        btnAssignDisable: function (btnKey) {
            var that = this;
            $.each(that.jsonInitConf[btnKey], function (k, v) {
                that.btnDisable(v);
            });
        }
    };
    return new Tools();
})(window.jQuery);

/**
 * 异步提交表单和message整合
 */
var ajaxSubmitAndMsg = (function ($) {
    if (!$().ajaxSubmit) {
        pagelog('ajaxSubmitAndMsg:ajaxSubmit不存在！');
        return;
    }
    return {
        init: function (objForm, isjump, url, callback) {
            var objForm = $(objForm);
            var pageContent = $('.page-content');
            callback = callback || function () {
                    pagelog(["call", "back:objForm", "success"]);
                };
            try {
                $("#dialogCancel").click();
                App.blockUI(pageContent);
                objForm.ajaxSubmit({
                    success: function (data, status, xhr, objForm) {
                        App.unblockUI(pageContent);
                        var baseUrl = $("base").attr("href") || '';
                        var msginfo = $.parseJSON(data),
                            msg = $.globalMessenger().post({
                                message: msginfo['msg'],
                                type: msginfo['success'] ? 'info' : 'error',
                                showCloseButton: true,
                                hideAfter: 3
                            });
                        if (objForm && msginfo['success']) {
                            if (isjump) {
                                var rurl = (undefined !== url) ? url : objForm.attr('data-method-url');
                                //判断是否是绝对路径
                                if (rurl && rurl.indexOf('/') !== 0 && rurl.indexOf('http') !== 0) {
                                    rurl = baseUrl + rurl;
                                }
                                window.location.href = rurl;
                            } else {
                                window.location.reload();
                            }
                        }
                        else {
                            if (typeof (callback) === 'function') {
                                callback(objForm);
                            }
                        }
                        ;
                    }
                });
            } catch (e) {
                pagelog(e);
            }
        }
    };
})(window.jQuery);

/**
 * dataPacker
 *
 * @access public
 * @return void
 */
var FormDatePicker = (function () {
    if (!jQuery().datepicker) {
        return;
    }

    $.extend($.fn.datepicker.dates, {
        cn: {
            days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
            daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
            daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
            months: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月",
                "10月", "11月", "12月"],
            monthsShort: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月",
                "9月", "10月", "11月", "12月"],
            meridiem: ["上午", "下午"],
            suffix: ["st", "nd", "rd", "th"],
            today: "今天"
        }
    });
    return {
        init: function (settings, selecter, callback) {
            var settings = settings || {};
            var selecter = selecter || ".date-picker";
            var callback = callback || function () {
                    pagelog(["call", "back", "success"]);
                };
            var defaultSet = {
                rtl: App.isRTL(),
                language: "cn",
                autoclose: true,
                format: 'yyyy-mm-dd'
            };
            var settings = $.extend(defaultSet, settings);
            $(selecter).datepicker(settings, callback);
        }
    };
})();

/**
 * datatimePacker
 *
 * @access public
 * @return void
 */
var FormDatetimePicker = (function () {
    if (!jQuery().datetimepicker) {
        return;
    }
    $.extend($.fn.datetimepicker.dates, {
        cn: {
            days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
            daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
            daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
            months: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
            monthsShort: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
            meridiem: ["上午", "下午"],
            suffix: ["st", "nd", "rd", "th"],
            today: "今天"
        }
    });
    return {
        init: function (settings, selecter, callback) {
            var settings = settings || {};
            var selecter = selecter || ".datetime-picker";
            var callback = callback || function () {
                    pagelog(["call", "back", "success"]);
                };
            var defaultSet = {
                isRTL: App.isRTL(),
                format: "yyyy-mm-dd hh:ii",
                autoclose: true,
                language: "cn",
                todayBtn: true,
                startDate: "2013-02-14 10:00",
                pickerPosition: (App.isRTL() ? "bottom-right" : "bottom-left"),
                minuteStep: 10
            };
            var settings = $.extend(defaultSet, settings);
            $(selecter).datetimepicker(settings, callback);
        }
    };
})();

/**
 * datatimePacker
 *
 * @access public
 * @return void
 */
var FormDatehourPicker = (function () {
    if (!jQuery().datetimepicker) {
        return;
    }
    $.extend($.fn.datetimepicker.dates, {
        cn: {
            days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
            daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
            daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
            months: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月",
                "10月", "11月", "12月"],
            monthsShort: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月",
                "9月", "10月", "11月", "12月"],
            meridiem: ["上午", "下午"],
            suffix: ["st", "nd", "rd", "th"],
            today: "今天"
        }
    });
    return {
        init: function (settings, selecter, callback) {
            var settings = settings || {};
            var selecter = selecter || ".datetime-picker";
            var callback = callback || function () {
                    pagelog(["call", "back", "success"]);
                };
            var defaultSet = {
                isRTL: App.isRTL(),
                format: "yyyy-mm-dd hh",
                autoclose: true,
                language: "cn",
                todayBtn: true,
                startDate: "2013-02-14 10",
                pickerPosition: (App.isRTL() ? "bottom-right" : "bottom-left"),
                minuteStep: 60
            };
            var settings = $.extend(defaultSet, settings);
            $(selecter).datetimepicker(settings, callback);
        }
    };
})();


/**
 * datatimePacker
 *
 * @access public
 * @return void
 */
var FormDatetimePickerIn = (function () {
    if (!jQuery().datetimepicker) {
        return;
    }
    $.extend($.fn.datetimepicker.dates, {
        cn: {
            days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
            daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
            daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
            months: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
            monthsShort: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
            meridiem: ["上午", "下午"],
            suffix: ["st", "nd", "rd", "th"],
            today: "今天"
        }
    });
    return {
        init: function (settings, selecter, callback) {
            var settings = settings || {};
            var selecter = selecter || ".datetime-picker";
            var callback = callback || function () {
                    pagelog(["call", "back", "success"]);
                };
            var defaultSet = {
                isRTL: App.isRTL(),
                format: "yyyy-mm-dd hh:ii",
                autoclose: true,
                language: "cn",
                todayBtn: true,
                startDate: "2013-02-14 10:00",
                pickerPosition: (App.isRTL() ? "bottom-right" : "bottom-left"),
                minuteStep: 1
            };
            var settings = $.extend(defaultSet, settings);
            $(selecter).datetimepicker(settings, callback);
        }
    };
})();
/**
 * Detail
 *
 * @access public
 * @return void
 */
var Detail = function (selecter) {
    var selecter = selecter || ".data_formDetail";
    return {
        init: function (callback) {
            var objForm = $(selecter),
                editType = objForm.attr("editType") || '',
                jsonDetail = objForm.attr("jsonDetail") || '',
                baseUrl = objForm.attr('data-method-url') || '',
                keyid = objForm.attr('data-keyid') || '',
                hosturl = $('base').attr('href') || '',
                callback = callback || function () {
                        pagelog(["call", "back:objForm", "success"]);
                    };
            //转化为绝对url
            if (baseUrl.indexOf('/') !== 0 && baseUrl.indexOf('http') !== 0) {
                baseUrl = hosturl + '/' + baseUrl;
            }
            switch (editType) {
                case 'add':
                    objForm.find('[data-disable]').attr('disabled', 'disabled');
                    objForm.attr('action', baseUrl + "/create");
                    break;
                case 'modify':
                    objForm.find('[data-disable]').attr('disabled', 'disabled');
                    objForm.attr('action', baseUrl + "/edit/" + keyid);
                    break;
                case 'detail':
                    objForm.find('.form-control').attr('disabled', 'disabled');
                    objForm.find(".submitBtn").remove();
                    break;
            }
            ;
            // 设置标签默认值
            if (jsonDetail) {
                Detail.setData(objForm, jsonDetail);
            } else {
                pagelog("未获取到jsonDetail");
            }
            ;

            if (typeof (callback) === 'function') {
                callback(objForm);
            }
        }
    };
};

Detail.setData = function (objForm, jsonStr) {
    try {
        var jsonDataInfo = $.parseJSON(jsonStr);
        for (var k in jsonDataInfo) {
            var axObj = objForm.find("[name=" + k + "]"),
                type = axObj.attr('type');
            if (Detail.util.isEmpty(jsonDataInfo[k]) || type == 'file') {
                continue;
            }
            if (axObj.length === 1) {
                var tag = axObj[0].tagName;
                if (tag == "SELECT") {
                    if (objForm.find("select[name=" + k + "]").hasClass("flexselect"))
                        $("#" + objForm.find("select[name=" + k + "]").attr("id") + "_flexselect").val(jsonDataInfo[k]);
                    objForm.find("select[name=" + k + "] option[value='" + jsonDataInfo[k] + "']").attr("selected", true);
                } else if (tag == "INPUT" && "checkbox" == type) {
                    if ("" != jsonDataInfo[k] && 0 != jsonDataInfo[k]) {
                        var checkboxObj = objForm.find('[name=' + k + ']');
                        checkboxObj.attr("checked", true);
                        $.uniform.update(checkboxObj);
                    }
                } else {
                    objForm.find('[name=' + k + ']').val(jsonDataInfo[k]);
                }
            } else if (axObj.length > 1) {
                switch (type) {
                    case 'radio':
                        objForm.find('input:radio[name="' + k + '"][value=' + jsonDataInfo[k] + ']').attr("checked", true);
                        break;
                    default:
                        // TODO 增加控件类型
                        pagelog("未实现的控件！");
                }
            }
        }
    } catch (e) {
        pagelog(e);
    }
};

Detail.util = {
    filterQuotes: function (str) {
        var str = new String(str);
        return str.replace(/["]+[']+/g, '');
    }
    , isEmpty: function (str) {
        if ('' !== str && null !== str && undefined !== str) {
            return false;
        } else {
            return true;
        }
    }
};

// 表单验证
var formValidate = function (selecter) {
    var formObj = $(".data_formDetail");
    if (selecter !== "" && typeof (selecter) === 'string') {
        formObj = $(selecter);
    } else {
        throw new TypeError("必须传入选择器字符串！");
    }
    // 绑定键盘enter键提交
    formObj.find('input').keypress(function (e) {
        if (e.which === 13) {
            if (formObj.validate().form()) {
                formObj.submit();
            }
            return false;
        }
    });
    $.extend($.validator.messages, {
        required: "必选字段",
        remote: "请修正该字段",
        email: "请输入正确格式的电子邮件",
        url: "请输入合法的网址",
        date: "请输入合法的日期",
        dateISO: "请输入合法的日期 (ISO).",
        number: "请输入合法的数字",
        digits: "只能输入整数",
        creditcard: "请输入合法的信用卡号",
        equalTo: "请再次输入相同的值",
        accept: "请输入拥有合法后缀名的字符串",
        maxlength: jQuery.validator.format("请输入一个长度最多是 {0} 的字符串"),
        minlength: jQuery.validator.format("请输入一个长度最少是 {0} 的字符串"),
        rangelength: jQuery.validator.format("请输入一个长度介于 {0} 和 {1} 之间的字符串"),
        range: jQuery.validator.format("请输入一个介于 {0} 和 {1} 之间的值"),
        max: jQuery.validator.format("请输入一个最大为 {0} 的值"),
        min: jQuery.validator.format("请输入一个最小为 {0} 的值")
    });
    function addAsteriskMark(valiObj) {
        valiObj.parents('td').prev('td').find('label.control-label').prepend('<span class="required">*</span>');
    }

    var rules = {}, msg = {}, attrSet = {};
    $(formObj).find('[data-validate]').each(
        function () {
            var name = $(this).attr('name')
                , validate = $(this).attr('data-validate')
                , message = $(this).attr('data-message')
                , validate = '{' + name + ':' + validate + '}';
            validate = eval('(' + validate + ')');
            $.extend(rules, validate);
            if (message) {
                message = '{' + name + ':' + message + '}';
                message = eval('(' + message + ')');
                $.extend(msg, message);
            }
            addAsteriskMark($(this));
        });
    attrSet = {
        "rules": rules,
        "massage": msg
    };
    return {
        init: function (settings) {
            var defaults = {
                errorElement: 'span', // default input error message container
                errorClass: 'help-block', // default input error message class
                focusInvalid: false, // do not focus the last invalid input
                ignore: "",
                invalidHandler: function (event, validator) { // display error
                    return false;
                },
                highlight: function (element) { // hightlight error inputs
                    $(element).addClass('has-error').css('border', '1px solid red'); // set error class to the
                },
                unhighlight: function (element) { // revert the change done by
                    $(element).removeClass('has-error').css('border', 'none'); // set
                },
                success: function (label) {
                },
                errorPlacement: function (error, element) {
                },
                submitHandler: function (formObj) {
                    ajaxSubmitAndMsg.init(formObj, true);
                }
            };
            var settings = $.extend(defaults, attrSet, settings);
            formObj.validate(settings);
        }
    };
};

/**
 * pagelog helper 日志输出
 *
 * @access public
 * @return void
 */
function pagelog() {
    var msg = '[page.define] ' + Array.prototype.join.call(arguments, '');
    if (window.console && window.console.log) {
        window.console.log(msg);
    } else if (window.opera && window.opera.postError) {
        window.opera.postError(msg);
    }
};

/**
 * loadjscssfile helper 动态加载js或css
 *
 * @param filename
 *            $filename
 * @param filetype
 *            $filetype
 * @access public
 * @return void
 */
function loadjscssfile(filename, filetype) {
    if (filetype === "js") {
        var fileref = document.createElement('script');
        fileref.setAttribute("type", "text/javascript");
        fileref.setAttribute("src", filename);
    } else if (filetype === "css") {
        var fileref = document.createElement('link');
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename);
    }
    if (typeof fileref !== "undefined") {
        document.getElementsByTagName("head")[0].appendChild(fileref);
    }
}

/**
 * 继承工具函数
 */
var extend = (function () {
    for (var p in {toString: null}) {
        return function extend(o) {
            for (var i = 1; i < arguments.length; i++) {
                var source = arguments[i];
                for (var prop in source)
                    o[prop] = source[prop];
            }
            return o;
        };
    }

    return function patched_extend(o) {
        for (var i = 1; i < arguments.length; i++) {
            var source = arguments[i];
            for (var prop in source)
                o[prop] = source[prop];
            for (var j = 0; j < protoprops.length; j++) {
                prop = protoprops[j];
                if (source.hasOwnProperty(prop))
                    o[prop] = source[prop];
            }
        }
        return o;
    };
    var protoprops = ['toString', 'valueOf', 'constructor', 'hasOwnProperty', 'isPrototyoeOf', 'propertyIsEnumberable', 'toLocaleString'];
}());

/**
 * 自动实例化工具条中的按钮==搜索参数赋值 TODO 搜索功能重构
 */
!(function ($) {
    function initBtn() {
        var btns = $('.actions').find('.btn[id]');
        var baseUrl = $("base").attr("href") || '';
        btns.each(function () {
            var options = {};
            options.href = $(this).attr('href');
            options.button = "#" + $(this).attr('id');
            if ($(this).hasClass("os_check")) {
                options.before = true;
            }
            //判断是否是绝对路径
            if (options.href.indexOf('/') !== 0 && options.href.indexOf('http') !== 0) {
                options.href = baseUrl + options.href;
            }
            $(this).removeAttr('href');
            BtnMaker.factory(options);
        });
    }

    function searchFilter() {
        var objSearch = $('#searchArea'), jsonStr = objSearch.attr('data-searchdata'), jsonObj;
        if (jsonStr !== "" && jsonStr !== undefined) {
            Detail.setData(objSearch, jsonStr);
        }
    }

    // INIT APP
    App.init();
    initBtn();
    searchFilter();
})(window.jQuery);
